package net.chasing.androidbaseconfig.view;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import net.chasing.androidbaseconfig.util.OneClickUtil;
import net.chasing.androidbaseconfig.widget.dialog.ProgressDialog;

import java.util.List;

/**
 * 注意：使用自定义{@link net.chasing.androidbaseconfig.adapter.BaseFragmentPagerAdapter}
 * 切换的时候是不会销毁Fragment的，只会调用onDestroyView，没有调用到onDestroy，
 * 所以在onCreate等步骤进行初始化时，需要进行判断，避免重复初始化
 */
public abstract class BaseMVCFragment<Binding extends ViewDataBinding> extends Fragment {
    protected OneClickUtil mOneClickUtil;
    protected Activity mActivity;
    protected boolean isCreateBySaveInstanceState;

    protected Binding mBinding;
    protected ProgressDialog dialog;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    protected boolean needReset; //判断是否需要重新设置所有属性

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mBinding == null) {
            mBinding = DataBindingUtil.inflate(inflater, bindLayout(), container, false);
            mBinding.setLifecycleOwner(this);
            needReset = true;
        } else {
            needReset = false;
        }
        return mBinding.getRoot();
    }

    protected abstract int bindLayout();

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = getActivity();
        if (savedInstanceState != null)
            isCreateBySaveInstanceState = true;
        initBeforeOnCreate(savedInstanceState);
        if (needReset) {
            mOneClickUtil = new OneClickUtil();
            initView();
            setListener();
        }
    }

    protected void initBeforeOnCreate(@Nullable Bundle savedInstanceState) {

    }

    protected abstract void initView();

    protected abstract void setListener();

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        changeUISize(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        changeUISize(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        mBinding = null;
        mActivity = null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    protected void changeUISize(boolean isChangeByConfiguration) {

    }

    public void removeAllFragment() {
        if (mOneClickUtil == null || mOneClickUtil.check("removeAllFragment" + this)) return;
        FragmentManager fm = getChildFragmentManager();
        Fragment fragment;
        List<Fragment> fragments = fm.getFragments();
        for (int i = 0; i < fragments.size(); i++) {
            fragment = fragments.get(i);
            if (fragment != null) {
                if (fragment instanceof BaseFragment)
                    ((BaseFragment<?, ?>) fragment).removeAllFragment();
                fm.beginTransaction().remove(fragment).commitAllowingStateLoss();
                fm.executePendingTransactions();
            }
        }
    }

    /**
     * 切换要显示的fragment，不进行push到fragment栈
     * 不控制fragment层级
     *
     * @param resId        布局id
     * @param showFragment 要显示的fragment
     */
    public void changeFragmentToShow(@IdRes int resId, Fragment showFragment, String showFragmentTag) {
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) { // 隐藏所有的fragment
            transaction.hide(fragment);
        }

        if (showFragment.isAdded()) {
            transaction.show(showFragment);
            if (!mActivity.isFinishing()) {
                transaction.commitAllowingStateLoss();
                fragmentManager.executePendingTransactions();
            }
        } else {
            try {
                Fragment fragmentByTag = fragmentManager.findFragmentByTag(showFragmentTag);
                if (fragmentByTag != null)
                    transaction.remove(fragmentByTag);
                transaction.add(resId, showFragment, showFragmentTag);
                transaction.show(showFragment);
                if (!mActivity.isFinishing()) {
                    transaction.commitAllowingStateLoss();
                    fragmentManager.executePendingTransactions();
                }
            } catch (Exception e) {
                transaction = fragmentManager.beginTransaction();
                transaction.show(showFragment);
                transaction.commitAllowingStateLoss();
                fragmentManager.executePendingTransactions();
            }
        }
    }

    private long showLoadingTime;

    public void showLoading() {
        if (getActivity() != null && getActivity().isFinishing()) return;

        FragmentManager fg = getChildFragmentManager();
        FragmentTransaction ft = fg.beginTransaction();
        if (dialog == null) {
            dialog = new ProgressDialog();
            dialog.setCancelable(true);
        }
        dialog.show(ft, getClass().getName());
        showLoadingTime = System.currentTimeMillis();
    }

    /*
    如果showLoading的时间与hideLoading的时间相差太接近可能导致在调用dismiss的时候dialog还没有正真显示出来
    而dismiss之后dialog才正真显示出来，所以进行时间差判断（如果相差0.3s内就调用hide则延迟处理）
    */
    public void hideLoading() {
        if (dialog != null && getActivity() != null && !getActivity().isFinishing()) {
            long time = System.currentTimeMillis();
            if (time - showLoadingTime < 300 && mHandler != null) {
                mHandler.postDelayed(() -> {
                    if (dialog != null && getActivity() != null && !getActivity().isFinishing()) {
                        dialog.dismiss();
                        dialog.onDestroy();
                        dialog = null;
                    }
                }, 300 - (time - showLoadingTime));
            } else {
                dialog.dismiss();
                dialog.onDestroy();
                dialog = null;
            }
        }
    }

    public void onPermissionGrant(String permission) {

    }

    public void onPermissionDeny(String permission) {

    }
}
